package com.example.imageloader.impl;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.imageloader.IImageLoader;
import com.example.imageloader.common.ImageOptions;

import java.io.File;
import java.lang.ref.SoftReference;

public class GlideImpl implements IImageLoader {

    @Override
    public void loadFileIntoImageView(Context context, File file, ImageView target, ImageOptions options) {
        loadImageView(context,file,target,options);
    }

    @Override
    public void loadResourceIntoImageView(Context context, int source, ImageView target, ImageOptions options) {
        loadImageView(context,source,target,options);
    }

    @Override
    public void loadByteArrayIntoImageView(Context context, byte[] bytes, ImageView target, ImageOptions options) {
        loadImageView(context,bytes,target,options);
    }

    @Override
    public void loadUriIntoImageView(Context context, Uri uri, ImageView target, ImageOptions options) {
        loadImageView(context,uri,target,options);
    }

    @Override
    public void loadIntoImageView(Context context, String url, ImageView target, ImageOptions options) {
        loadImageView(context,url,target,options);
    }

    /**
     * 加载图片到指定Imageview上
     * @param context
     * @param source
     * @param target
     * @param options
     */
    private void loadImageView(Context context,Object source,ImageView target,ImageOptions options){
        SoftReference<Context> ctx = new SoftReference<>(context);
        RequestBuilder<Drawable> builder = Glide.with(ctx.get()).load(source);
        setBuilderOptions(builder,options);
        builder.into(target);
    }

    /**
     * 设置图片参数
     * @param builder
     * @param config
     */
    private void setBuilderOptions(RequestBuilder<Drawable> builder,ImageOptions config){
        if (config == null){
            return;
        }
        RequestOptions options = new RequestOptions();
        if (config.getPlaceImage() != 0){
            options.placeholder(config.getPlaceImage());
        }
        if (config.getErrorImage() != 0){
            options.error(config.getErrorImage());
        }
        if (config.getImageSize() != null){
            if (config.getImageSize().length != 2){
                throw new IllegalStateException("please set imageSize length size is 2");
            }
            options.override(config.getImageSize()[0],config.getImageSize()[1]);
        }
        if (config.isSkipMemoryCache()){
            options.skipMemoryCache(true);
        }
        if (config.isSkipDiskCache()){
            options.diskCacheStrategy(DiskCacheStrategy.NONE);
        }

        builder.apply(options);
    }

}
